from rest_framework import serializers
from xyz.models import Question, Label, Reply, User, Comment, Spit


# # 所有标签
class LabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = ['id', 'label_name']


# 发布问题
class QuestionSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Question
        fields = '__all__'


# 等待回答
class AwaitSerializer(serializers.ModelSerializer):
    labels = serializers.StringRelatedField(many=True)
    user = serializers.StringRelatedField()

    class Meta:
        model = Question
        fields = '__all__'
        # exclude=['labels']


# 热门回答
class HotSerializer(serializers.ModelSerializer):
    labels = serializers.StringRelatedField(label='标签名', many=True)
    user = serializers.StringRelatedField()

    class Meta:
        model = Question
        exclude = ['content', 'solve', 'thumbup', 'updatetime']


# 最新回答
class NewSerializer(serializers.ModelSerializer):
    labels = serializers.StringRelatedField(label='标签名', many=True)
    user = serializers.StringRelatedField()

    class Meta:
        model = Question
        exclude = ['content', 'solve', 'thumbup', 'updatetime']


# # 问答详情
# class Usersializer(serializers.ModelSerializer):
#     class Meta:
#         model=User
#         fields=['id','username','avatar']
#
#
# class QuestionsSerializer(serializers.ModelSerializer):
#     labels=serializers.StringRelatedField(many=True)
#     class Meta:
#         model=Question
#         fields='__all__'


class AnswerSerializer(serializers.ModelSerializer):
    subs = serializers.StringRelatedField(many=True)

    class Meta:
        model = Reply
        fields = '__all__'
        depth = 1

class CommentSerializer(serializers.ModelSerializer):
    # subs=serializers.StringRelatedField(many=True)
    # comment_question=QuestionsSerializer(read_only=True)
    # user=Usersializer()
    labels = serializers.StringRelatedField(many=True)
    # comment_question = serializers.StringRelatedField(many=True)
    answer_question = AnswerSerializer(many=True)
    user = serializers.StringRelatedField()

    class Meta:
        model = Question
        fields = '__all__'

    # 发布吐槽


class SpitSerializer(serializers.ModelSerializer):
    class Meta:
        model = Spit
        fields = '__all__'

    def validate_content(self, attrs):
        content = attrs['content']
        print(content)
        try:
            spit = Spit.objects.get(content=content)
        except Spit.DoesNotExist:
            return serializers.ValidationError('错误')
        attrs['content'] = spit
        return attrs

    def create(self, validated_data):
        spit = Spit.objects.create(**validated_data)
        return spit
